package com.tao.utilslib.log.logsave.task;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;

public class AddHeadSaveTask extends BaseAddTask {
    String logPah;
    String logStr;
    long maxLog;

    public AddHeadSaveTask(String logPah, String logStr, long maxLog) {
        this.logPah = logPah;
        this.logStr = logStr;
        this.maxLog = maxLog;
    }

    @Override
    public void run() {
        saveLogHead(logPah, appendLogHead(logStr), maxLog);
    }


    public   synchronized void saveLogHead(String logPah, String logStr, long maxLog) {

        FileOutputStream buffOut = null;
        FileInputStream buffIn = null;
        FileInputStream logInput = null;
        FileOutputStream logOut = null;
        try {
            File file = new File(logPah);
            File buffFile = new File(file.getParentFile().getAbsolutePath() + "/" + file.getName() + "_buff");
            if (!buffFile.exists()) {
                buffFile.getParentFile().mkdirs();
                buffFile.createNewFile();
            }

            buffOut = new FileOutputStream(buffFile);
            buffIn = new FileInputStream(buffFile);
            logInput = new FileInputStream(file);

            int len = 0;
            byte[] buff = new byte[20480];

            while ((len = logInput.read(buff)) > 0) {
                buffOut.write(buff, 0, len);
            }
            logInput.close();

            FileWriter fileWriter = new FileWriter(file);
            fileWriter.flush();
            fileWriter.close();

            logOut = new FileOutputStream(file, true);
            logOut.write(logStr.getBytes());
            logOut.write("\n".getBytes());
            int totalLenth = 0;
            while ((len = buffIn.read(buff)) > 0) {
                logOut.write(buff, 0, len);
                totalLenth += len;
                if (totalLenth > maxLog) {
                    break;
                }
            }


      
            closeIo(buffOut);
            closeIo(buffIn);
            
            
            FileWriter buffwr = new FileWriter(buffFile);
            buffwr.flush();
            closeIo(buffwr);

            buffFile.delete();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            closeIo(buffOut);
            closeIo(buffIn);
            closeIo(logOut);
            closeIo(logInput);
 

        }
    }
}
